<template>
  <div class='user'>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top: 15px;">
      <!--输入框   添加按键的修饰符 -->
      <el-input placeholder="请输入内容" class="input-with-select search-input" v-model='searchValue' @keydown.native.enter='searchUserList'>
        <el-button slot="append" icon="el-icon-search" @click='searchUserList'></el-button>
      </el-input>
      <el-button type="success" plain @click="showAddDialog">添加用户</el-button>
    </div>
    <!-- 带边框表格 -->
    <template>
      <el-table :data="userList" border style="width: 100%; margin-top:10px;">
        <!-- #号表格在单选表格中 -->
        <el-table-column type="index" width="50">
        </el-table-column>
        <!-- 带边框表格 -->
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change='changeUserState(scope.row)'>
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作表格:在自定义表格中 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- plain:属性来定义 Button 的样式。 -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
            <el-button type="primary" icon="el-icon-edit" plain @click='showEditDialog(scope.row)'></el-button>
            </el-tooltip>
             <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
            <el-button type="primary" icon="el-icon-delete" plain @click='showDelDialog(scope.row.id)'></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
            <el-button type="primary" icon="el-icon-check" plain @click='showGrantDialog(scope.row)'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-pagination
    class='user-page'
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="1" :page-sizes="[10, 20, 30, 40]"
    :page-size="pagesize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total">
    </el-pagination>
    <!-- 添加用户对话框 -->
    <el-dialog title="用户注册" :visible.sync="addDialogFormVisible">
      <el-form :model="addform" label-width="100px" :rules='rules' ref='addform'>
        <el-form-item label="用户名:" prop='username'>
          <el-input v-model="addform.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop='password'>
          <el-input v-model="addform.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop='email'>
          <el-input v-model="addform.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop='mobile'>
          <el-input v-model="addform.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserSubmit('addform')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加编辑的操作 -->
    <el-dialog title="用户编辑" :visible.sync="editDialogFormVisible">
      <el-form :model="editform" label-width="100px" :rules='rules' ref='editform'>
        <el-form-item label="用户名:" prop='username'>
          <el-input v-model="editform.username" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop='email'>
          <el-input v-model="editform.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop='mobile'>
          <el-input v-model="editform.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit('editform')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配用户角色的操作 -->
     <el-dialog title="职位分配" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantform" label-width="100px" :rules='rules' ref='grantform'>
        <el-form-item label="用户名:" prop='username'>
          <el-input v-model="grantform.username" auto-complete="off" disabled style='width:88px'></el-input>
        </el-form-item>
        <el-form-item label="角色:">
          <el-select v-model="grantform.rid" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantUserSubmit('grantform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getUserList, addUser, editUser, DeleteUser, getRolesList, grantUser, changeuserstate } from '@/api/index.js'
export default {
  data () {
    return {
      // value2: true,
      pagenum: 1,
      pagesize: 10,
      total: 0,
      searchValue: '',
      userList: [],
      rolesList: [],
      // 设置用户添加框
      addDialogFormVisible: false,
      // // 设置编辑添加框
      editDialogFormVisible: false,
      // 设置分配的对话框
      grantDialogFormVisible: false,
      addformLabelWidth: '100',
      addform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editform: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      grantform: {
        username: '',
        id: '',
        rid: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
        ],
        mobile: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 1.分页事件:当每页显示的记录数设置变化的时候触发
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 当每页显示的记录数设置变化的时候触发函数
      this.initList()
    },
    // 2.分页事件:当当前页码发生变化的时候触发
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      // 当用户页码发生改变的时候触发函数
      this.initList()
    },
    // 3.实现数据的搜索
    searchUserList () {
      // 按下enter健的时候触发函数里的数据查询对应的数据
      this.initList()
    },
    // 4.添加用户对话框
    showAddDialog () {
      this.addDialogFormVisible = true
    },
    // 5.实现用户数据的添加
    addUserSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 实现数据的新增
          addUser(this.addform)
            .then((res) => {
              console.log(res)
              // 当响应码等于201的时候,则是添加成功
              if (res.meta.status === 201) {
                // 提示用户添加成功
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
                // 将新增的数据添加到函数列表中
                this.initList()
                // 成功之后清空对话框的数据
                this.addform = {}
                // 点击确认后关闭对话框
                this.addDialogFormVisible = false
              } else {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
              }
            })
        } else {
          this.$message({
            type: 'warning',
            message: '数据输入不合法'
          })
        }
      })
    },
    //  6.打开编辑用户对话框--加载默认数据
    showEditDialog (row) {
      // 调用参数,查看里面的数据,实现显示再编辑列表中
      // console.log(row)
      this.editDialogFormVisible = true
      this.editform.username = row.username
      this.editform.email = row.email
      this.editform.mobile = row.mobile
      this.editform.id = row.id
    },
    // 7.实现用户的编辑操作
    editUserSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 实现数据的编辑
          editUser(this.editform)
            .then((res) => {
              console.log(res)
              // 当响应码等于201的时候,则是编辑成功
              if (res.meta.status === 200) {
                // 提示用户编辑成功
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
                // 将编辑的数据添加到函数列表中
                this.initList()
                // 点击确认后关闭对话框
                this.editDialogFormVisible = false
              } else {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
              }
            })
        } else {
          this.$message({
            type: 'warning',
            message: '数据输入不合法'
          })
        }
      })
    },
    // 8.点击删除按钮提示用户是否删除
    showDelDialog (id) {
      // console.log(row)
      // this.deleteId = row.id
      // this.$confirm(`此操作将永久删除该id号${row.id}, 是否继续?`, '提示', {
      this.$confirm(`此操作将永久删除该id号${id}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // DeleteUser(this.deleteId)
          DeleteUser(id)
            .then((res) => {
              console.log(res)
              if (res.meta.status === 200) {
                // 提示用户添加成功
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
                // 将新增的数据添加到函数列表中
                this.initList()
              } else {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 9.点击分配弹出对话框
    showGrantDialog (row) {
      console.log(row)
      // 让框框显示
      this.grantDialogFormVisible = true
      // 获取用户名
      this.grantform.username = row.username
      // 获取用户id
      this.grantform.id = row.id
      // 加载角色默认数据--下拉列表的默认数据加载
      getRolesList()
        .then((res) => {
          console.log(res)
          this.rolesList = res.data
        })
    },
    // 10.提交角色授权
    grantUserSubmit () {
      // console.log(this.grantform)
      if (!this.grantform.rid) {
        this.$message({
          type: 'warning',
          message: '请先选择角色,否则提交失败!'
        })
        return
      }
      grantUser(this.grantform)
        .then((res) => {
          console.log(res)
          if (res.meta.status === 200) {
            // 提示用户分配成功
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
            this.initList()
            // 选择完角色分配之后清空选择框的数据
            this.grantform = {}
            // 点击确认后关闭对话框
            this.grantDialogFormVisible = false
          } else {
            // 提示用户分配失败
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
          }
        })
    },
    // 11.点击切换用户状态
    changeUserState (row) {
      console.log(row)
      changeuserstate({uid: row.id, type: row.mg_state})
        .then((res) => {
          console.log(res)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
          } else {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
          }
        })
    },
    // 12.加载用户列表的数据
    initList () {
      getUserList({
        params: {
          query: this.searchValue,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      }).then(res => {
        // console.log(res)
        this.userList = res.data.users
        // 获取用户的总条数
        this.total = res.data.total
      })
    }
  },
  // 在页面加载完毕就立刻获取数据
  mounted () {
    // this.initList()
    // 一开始获取当前页数的总条数渲染
    this.handleSizeChange(this.pagesize)
  }
}
</script>
<style lang="scss" scoped>
.user {
  .search-input {
    width: 300px;
  }
  .user-page {
    // background-color: rgb(214, 210, 210);
    margin-top: 10px;
  }
}
</style>
